import os

from quart import Quart
import asyncio
import time
from api import PingApi
from config.logger_config import logger

app = Quart(__name__)
app.register_blueprint(PingApi.ping_api_bt)

# 同步方法会 阻塞当前事件循环线程，导致其他异步任务无法执行。
# 为了不卡死整个应用，Quart（通过 Hypercorn/uvicorn）会 隐式启用线程池 来运行同步方法。
@app.route('/get3', methods=['GET'])
def hello3():
    worker_pid = os.getpid()  # 获取当前worker的PID
    logger.debug(f"hello2 api {time.time()} by worker PID:{worker_pid}")
    time.sleep(3)
    return f'Hello2, World! {time.time()} by worker PID:{worker_pid}'
# async def 所有请求都在 同一个事件循环线程 中处理（通过协程切换）
@app.route('/get2', methods=['GET'])
async def hello2():
    worker_pid = os.getpid()  # 获取当前worker的PID
    logger.debug(f"hello2 api {time.time()} by worker PID:{worker_pid}")
    time.sleep(3)
    return f'Hello2, World! {time.time()} by worker PID:{worker_pid}'

@app.route('/get', methods=['GET'])
async def hello():
    worker_pid = os.getpid()  # 获取当前worker的PID
    logger.debug(f"hello api {time.time()} by worker PID:{worker_pid}")
    await asyncio.sleep(3)
    return f'Hello, World! {time.time()} by worker PID:{worker_pid}'
# hypercorn quart_web:app --bind 0.0.0.0:5600 -w 1  -k asyncio
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5600)